package com.sn.author.filter.advice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.sn.author.common.exception.EncodeException;
import com.sn.author.utils.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Component
@ControllerAdvice(basePackages = "com.sn.author.controller")
@Slf4j
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String bodyStr = JSON.toJSONString(body, SerializerFeature.DisableCircularReferenceDetect);
        log.debug("start encode response:{}", JSON.toJSONString(body));
        String encodeStr;
        try {
            encodeStr = AESUtil.encrypt(bodyStr);
            log.debug("end encode response:{}",encodeStr);
        } catch (Exception e) {
            throw new EncodeException("encode response body exception...");
        }
        return encodeStr;
    }
}
